﻿// MIT License
//
// Copyright (c) 2021-present zuohuaijun, Daming Co.,Ltd and Contributors
//
// 电话/微信：18020030720 QQ群1：87333204 QQ群2：252381476

using Admin.NET.Application.Const;
using Admin.NET.Core.Service;
using Admin.Net.InformationPlatform.Entity;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using Nest;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Admin.NET.Core;
using Admin.Net.InformationPlatform.Service.SRM.Dto;
using Furion.FriendlyException;
using Admin.Net.InformationPlatform.Entity.Maintenance;
using Admin.Net.InformationPlatform.Service.Maintenance.Dto;

namespace Admin.Net.InformationPlatform.Service.Maintenance 
{
    /// <summary>
    /// 运维平台-问题清单管理
    /// </summary>
    [ApiDescriptionSettings(groups: "Maintenance", Name = "问题清单管理", Tag = "问题清单管理", Order = 200)]

    public class YWPTQuestionService : IDynamicApiController, ITransient
    {
        private readonly SysUserRoleService _sysUserRoleService;
        /// <summary>
        /// 单例数据链接
        /// </summary>
        ISqlSugarClient db;
        /// <summary>
        /// T100数据库
        /// </summary>
        private SqlSugarProvider _T100Db;
        private SqlSugarProvider _SjDb;
        private SqlSugarProvider _plm;
        private SqlSugarProvider _Dilon;


        /// <summary>
        /// 用户信息
        /// </summary>
        TokenUser _User;
        /// <summary>
        /// 成品仓库管理模块
        /// </summary>
        /// <param name="db"></param>
        public YWPTQuestionService(ISqlSugarClient db, SysUserRoleService sysUserRoleService)
        {
            this.db = db;
            this._T100Db = this.db.AsTenant().GetConnection(T100TestArea.ConfigId);
            this._SjDb = this.db.AsTenant().GetConnection(SJDB.ConfigId);
            this._plm = this.db.AsTenant().GetConnection(PLM.ConfigId);
            this._Dilon = this.db.AsTenant().GetConnection(Dilon.ConfigId);
            // 获取 `Jwt` 存储的信息 企业编号与据点信息
            _User = Util.SjCommonUtil.GetT100UserTokenInfo(_T100Db, _Dilon);
            _sysUserRoleService = sysUserRoleService;

        }
        /// <summary>
        ///  获取问题清单列表-分页
        /// </summary>
        /// <returns></returns>
        [HttpPost("/YWPT/GetQuestionPagedList")]
        public async Task<SqlSugarPagedList<YWPT_QUESTIONS>> GetMouldPagedList(YWPTQuestionInput input)
        {
           
            var output = await _SjDb.Queryable<YWPT_QUESTIONS>()
.Where(l => l.ISDELETE == 0)
.WhereIF(!string.IsNullOrEmpty(input.CLASSIFICATION), (l) => (l.CLASSIFICATION.Contains(input.CLASSIFICATION)))//问题分类
.WhereIF(!string.IsNullOrEmpty(input.DESCRIPTION), (l) => (l.DESCRIPTION.Contains(input.DESCRIPTION)))//问题描述

.OrderBy(l => l.CREATETIME, OrderByType.Desc) //创建日期排序
.Select(l => new YWPT_QUESTIONS
{
   ID= l.ID,
   CLASSIFICATION = l.CLASSIFICATION,
   DESCRIPTION = l.DESCRIPTION,
   SOLUTION = l.SOLUTION,
   CREATETIME =l.CREATETIME


}).ToPagedListAsync(input.Page, input.PageSize);
            return output;
        }
        /// <summary>
        /// 增加问题清单列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("/YWPT/AddQuestion")]
        public async Task<string> AddQuestion(YWPT_QUESTIONS input)
        {
            
            var details = new YWPT_QUESTIONS
            {
                ID = Guid.NewGuid().ToString("N"),
                CLASSIFICATION = input.CLASSIFICATION,
                DESCRIPTION = input.DESCRIPTION,
                SOLUTION = input.SOLUTION,
                ISDELETE = 0,
                CREATETIME = DateTime.Now
            };

            #region 插入事务
            try
            {
                //开启事务
                _SjDb.Ado.BeginTran();
                int cnt = await _SjDb.Insertable<YWPT_QUESTIONS>(details).ExecuteCommandAsync();

                if (cnt == 0)
                {
                    throw Oops.Oh($"新建任务失败！");
                }
                //提交事务
                _SjDb.Ado.CommitTran();
                return "插入成功";
            }
            catch (Exception e)
            {
                //回滚事务
                _SjDb.Ado.RollbackTran();
                throw Oops.Oh($"异常：{e.Message}");
            }
            #endregion

        }
        /// <summary>
        /// 问题清单更改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/YWPT/UpdateQuestion")]
        public async Task<string> UpdateQuestion(YWPT_QUESTIONS input)
        {

            //判断单据存在
            int cnt = await _SjDb.Queryable<YWPT_QUESTIONS>()
                .Where(a => a.ID == input.ID)
                .Select(a => a.ID)
                .CountAsync();
                if (cnt!=1)//允许修改数据
                {
                    throw Oops.Oh("没有要更改的数据！");
                }
                else
                {
                    //提交
                    try
                    {
                        _SjDb.Ado.BeginTran();
                        int count = await _SjDb.Updateable<YWPT_QUESTIONS>()
                            .SetColumns(a => a.CLASSIFICATION == input.CLASSIFICATION)
                            .SetColumns(a => a.DESCRIPTION == input.DESCRIPTION)
                            .SetColumns(a => a.SOLUTION == input.SOLUTION)
                            .Where(a => a.ID == input.ID)

                            .ExecuteCommandAsync();

                        if (count != 1)
                        {
                            throw Oops.Oh("修改失败！");
                        }
                        _SjDb.Ado.CommitTran();
                        return "修改成功！";
                    }
                    catch (Exception e)
                    {
                        _SjDb.Ado.RollbackTran();
                        throw Oops.Oh($"异常：{e.Message}");
                    }
                }

           
        }
        /// <summary>
        /// 问题清单删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/YWPT/DeleteQuestion")]
        public async Task<string> DeleteQuestion(YWPTQuestionDelete input)
        {
            //判断单据存在
            int cnt = await _SjDb.Queryable<YWPT_QUESTIONS>()
                .Where(a => a.ID == input.ID)
                .Select(a => a.ID)
                .CountAsync();
            if (cnt == 0)
            {
                throw Oops.Oh("任务不存在，驳回！");
            }
            else
            {
                //提交
                try
                {
                    _SjDb.Ado.BeginTran();
                    int count = await _SjDb.Updateable<YWPT_QUESTIONS>()
                        .SetColumns(a => a.ISDELETE == 1)
                        .Where(a => a.ID == input.ID)
                        .ExecuteCommandAsync();

                    if (count != 1)
                    {
                        throw Oops.Oh("删除失败！");
                    }
                    _SjDb.Ado.CommitTran();
                    return "删除成功！";
                }
                catch (Exception e)
                {
                    _SjDb.Ado.RollbackTran();
                    throw Oops.Oh($"异常：{e.Message}");
                }
            }
        }

    }
}
